class Solution {
public:
    vector<int> sortArray(vector<int>& nums) {
        // key值取随机数时，时间复杂度为NlogN
        srand(time(NULL));
        qsort(nums, 0, nums.size() - 1);
        return nums;
    }

    int getRandom(vector<int>& nums, int l, int r) {
        int ra = rand();
        int key = nums[ra % (r - l + 1) + l];
        return key;
    }

    void qsort(vector<int>& nums, int l, int r) {
        if (l >= r)
            return;

        // 数组分三块
        int key = getRandom(nums, l, r);
        int left = l - 1;
        int right = r+1;
        int i = l;
        while (i < right) {
            if (nums[i] < key) {
                swap(nums[++left], nums[i++]);
            } else if (nums[i] == key) {
                i++;
            } else {
                swap(nums[--right], nums[i]);
            }
        }
        // 递归排序左右区间
        qsort(nums, l, left);
        qsort(nums, right, r);
    }
};
